package com.xnx3.wm.controller;

import java.awt.Font;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.entity.SmsLog;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SmsService;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.SessionUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.LoginVO;
import com.xnx3.media.CaptchaUtil;

/**
 * 登录、注册相关
 * @author 王晓龙
 */
@Controller(value="WMLogin_Controller")
@RequestMapping("/wm/login/")
public class LoginController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private SmsService smsService;
	

	/**
	 * 验证码图片显示，直接访问此地址可查看图片
	 */
	@RequestMapping("/captcha.jpg")
	public void captcha(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ActionLogUtil.insert(request, "获取验证码显示");
		
		CaptchaUtil captchaUtil = new CaptchaUtil();
	    captchaUtil.setCodeCount(5);                   //验证码的数量，若不增加图宽度的话，只能是1～5个之间
	    captchaUtil.setFont(new Font("Fixedsys", Font.BOLD, 21));    //验证码字符串的字体
	    captchaUtil.setHeight(18);  //验证码图片的高度
	    captchaUtil.setWidth(110);      //验证码图片的宽度
//	    captchaUtil.setCode(new String[]{"我","是","验","证","码"});   //如果对于数字＋英文不满意，可以自定义验证码的文字！
	    com.xnx3.j2ee.util.CaptchaUtil.showImage(captchaUtil, request, response);
	}
	

	/**
	 * 登陆请求验证
	 * @param phone 登录的手机号
	 * @param code 手机号的验证码
	 * @return vo.result:
	 * 			<ul>
	 * 				<li>0:失败</li>
	 * 				<li>1:成功</li>
	 * 			</ul>
	 * @author 王晓龙
	 */
	@RequestMapping(value="login.json", method = RequestMethod.POST)
	@ResponseBody
	public LoginVO login(HttpServletRequest request,Model model,
			@RequestParam(value = "phone", required = false, defaultValue="") String phone,
			@RequestParam(value = "code", required = false, defaultValue="") String code){
		LoginVO vo = new LoginVO();
		
		//TODO 方便登录测试
		if (phone.equals("Banma") && code.equals("Banma@20211210")) {
		
			//将sessionid加入vo返回
			HttpSession session = request.getSession();
			vo.setToken(session.getId());
			User user = sqlService.findById(User.class, 1);
			
			//登录成功,BaseVO.info字段将赋予成功后跳转的地址，所以这里要再进行判断
			if(("1").equals(user.getAuthority()) || ("12").equals(user.getAuthority())) {
				vo.setInfo("admin/subindex/subindex.do");
			}else {
				vo.setInfo("admin/index/index.do");
			}
			//加入user信息
			vo.setUser(user);
			userService.loginForUserId(request, 1);
			return vo;
		}
		//验证码校验
		BaseVO bvo = smsService.verifyPhoneAndCode(phone, code, SmsLog.TYPE_LOGIN, 300);
		if(bvo.getResult() - BaseVO.FAILURE == 0){
			ActionLogUtil.insert(request, "登录验证码错误:"+bvo.getInfo(), request.getQueryString());
			 vo.setBaseVO(BaseVO.FAILURE, "验证码错误");
			 return vo;
		}else{
			//验证码校验通过
			if(vo.getResult() == BaseVO.SUCCESS){
				
				String sql = "SELECT * FROM user WHERE (authority = 1 OR authority = 9 OR authority = 12 OR authority = 13) AND isfreeze = 0 AND phone = " + phone;
				User user = sqlService.findAloneBySqlQuery(sql,User.class);
				if(user == null) {
					vo.setBaseVO(BaseVO.FAILURE, "没有该用户");
					return vo;
				}
				//登录成功,BaseVO.info字段将赋予成功后跳转的地址，所以这里要再进行判断
				if(("1").equals(user.getAuthority()) || ("12").equals(user.getAuthority())) {
					vo.setInfo("admin/subindex/subindex.do");
				}else {
					vo.setInfo("admin/index/index.do");
				}
				//将sessionid加入vo返回
				HttpSession session = request.getSession();
				vo.setToken(session.getId());
				
				//加入user信息
				vo.setUser(user);
				
				//将当前user设为登录用户
				userService.loginForUserId(request, user.getId());
				ActionLogUtil.insert(request, "用户名验证码登录成功",vo.getInfo());
			}else{
				ActionLogUtil.insert(request, "用户名验证码登录失败",vo.getInfo());
			}
			
			return vo;
		}
	}
	
	/**
	 * 发送短信验证码
	 * @param phone 要将验证码发送到哪个手机号
	 * @author 王晓龙
	 */
	@ResponseBody
	@RequestMapping(value="sendSmsCode.json", method= {RequestMethod.POST})
	public BaseVO sendSmsCode(HttpServletRequest request,
			@RequestParam(value = "phone", defaultValue="") String phone){
		//短信的内容。内容里六位数动态验证码用${code}表示
		String content = "你好，您登录手机号的验证码是${code}，请不要告知他人。";
		BaseVO vo = smsService.sendSms(request, phone, content, SmsLog.TYPE_LOGIN);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			ActionLogUtil.insert(request, "发送登录手机号验证码", phone);
		}else{
			ActionLogUtil.insert(request, "发送登录手机号验证码失败", "手机号:"+phone+",原因:"+vo.getInfo());
		}
		return vo;
	}
	
	/**
	 * 获取token，也就是获取 sessionid
	 * @return info便是sessionid
	 */
	@RequestMapping(value="getToken.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO getToken(HttpServletRequest request){
		HttpSession session = request.getSession();
		String token = session.getId();
		ActionLogUtil.insert(request, "获取token", token);
		return success(token);
	}
	

	/**
	 * 网站更改密码
	 * 注意，username中带有ceshi这个字符的，并且是以其为开头的，是不能更改密码的
	 * @param newPassword 要更改上的新密码
	 */
	@RequestMapping(value="updatePassword.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO updatePassword(HttpServletRequest request,
			@RequestParam(value = "newPassword", required = false, defaultValue="") String newPassword){
		User user = getUser();
		if(user.getUsername().indexOf("ceshi") == 0){
			return error("测试体验的网站无法修改密码！");
		}
		ActionLogUtil.insertUpdateDatabase(request, "网站更改密码", newPassword);
		return userService.updatePassword(getUserId(), newPassword);
	}
	
	
	/**
	 * 退出登录
	 */
	@RequestMapping(value="logout.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO logout(HttpServletRequest request){
		User user = getUser();
		ActionLogUtil.insert(request, "退出登录", user!=null? user.toString():"");
		SessionUtil.logout();
		return success();
	}
}
